/*
 * lock.c
 *
 *  Created on: 2016-11-10
 *      Author: jared
 */

#include "constants.h"
#include "types.h"
#include "defs.h"
#include "x86.h"
#include "proc.h"

void acquire(uint *lock) {
	pushcli();
	while (xchg(lock, 1) != 0)
		;
}

void release(uint *lock) {
	xchg(lock, 0);
	popcli();
}

void pushcli(void) {
	int eflags;

	eflags = readeflags();
	cli();
	if (cpu->ncli++ == 0)
		cpu->oldif = eflags & FL_IF;
}

void popcli(void) {
	if (readeflags() & FL_IF)
		panic("popcli - interruptible");
	if (--cpu->ncli < 0)
		panic("popcli");
	if (cpu->ncli == 0 && cpu->oldif)
		sti();
}
